<template>
  <div class="trace-container">
    <div class="trace-header">
      <h1>茶叶溯源查询</h1>
      <p>输入批次ID，查看完整的茶叶供应链信息</p>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-input
          v-model="searchId"
          placeholder="请输入茶叶批次ID，例如：TEA20241215ABC123"
          size="large"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prepend>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button type="primary" @click="handleSearch" :loading="searching">
              查询
            </el-button>
          </template>
        </el-input>
      </el-card>
    </div>

    <!-- 查询结果 -->
    <div v-if="batchData" class="result-section">
      <!-- 基本信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <el-icon><Coffee /></el-icon>
            <span>茶叶基本信息</span>
            <el-tag :type="getStatusTagType(batchData.status)" class="status-tag">
              {{ getStatusLabel(batchData.status) }}
            </el-tag>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <div class="info-item">
              <label>批次ID：</label>
              <span class="batch-id">{{ batchData.batchId }}</span>
              <el-button text type="primary" @click="copyBatchId">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
            <div class="info-item">
              <label>茶叶名称：</label>
              <span>{{ batchData.name }}</span>
            </div>
            <div class="info-item">
              <label>茶叶品种：</label>
              <span>{{ batchData.variety }}</span>
            </div>
            <div class="info-item" v-if="batchData.grade">
              <label>茶叶等级：</label>
              <span>{{ batchData.grade }}</span>
            </div>
          </el-col>
          <el-col :xs="24" :md="12">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(batchData.createdAt) }}</span>
            </div>
            <div class="info-item" v-if="batchData.description">
              <label>产品描述：</label>
              <p class="description">{{ batchData.description }}</p>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 溯源链条 -->
      <el-card class="trace-chain-card">
        <template #header>
          <div class="card-header">
            <el-icon><Connection /></el-icon>
            <span>溯源链条</span>
          </div>
        </template>
        
        <el-timeline>
          <!-- 创建阶段 -->
          <el-timeline-item
            timestamp="创建"
            type="primary"
            :hollow="batchData.status === 'created'"
          >
            <el-card class="timeline-card">
              <h4>批次创建</h4>
              <p>创建时间：{{ formatDateTime(batchData.createdAt) }}</p>
              <p v-if="batchData.createdBy">创建者：{{ batchData.createdBy.username }}</p>
            </el-card>
          </el-timeline-item>

          <!-- 生产阶段 -->
          <el-timeline-item
            v-if="batchData.production?.harvestDate"
            timestamp="生产"
            type="success"
            :hollow="batchData.status === 'production'"
          >
            <el-card class="timeline-card">
              <h4>生产记录</h4>
              <div class="production-info">
                <div class="info-group">
                  <h5>产地信息</h5>
                  <p>产地：{{ batchData.production.origin?.province }} {{ batchData.production.origin?.city }}</p>
                  <p v-if="batchData.production.origin?.county">
                    县区：{{ batchData.production.origin.county }}
                  </p>
                </div>
                <div class="info-group">
                  <h5>生产信息</h5>
                  <p>采摘日期：{{ formatDate(batchData.production.harvestDate) }}</p>
                  <p v-if="batchData.production.processingDate">
                    加工日期：{{ formatDate(batchData.production.processingDate) }}
                  </p>
                  <p v-if="batchData.production.processingMethod">
                    加工工艺：{{ batchData.production.processingMethod }}
                  </p>
                  <p v-if="batchData.production.weight">
                    重量：{{ batchData.production.weight }}kg
                  </p>
                </div>
              </div>
            </el-card>
          </el-timeline-item>

          <!-- 物流阶段 -->
          <el-timeline-item
            v-for="(logistics, index) in batchData.logistics || []"
            :key="`logistics-${index}`"
            timestamp="物流"
            type="warning"
            :hollow="batchData.status === 'logistics'"
          >
            <el-card class="timeline-card">
              <h4>物流记录 - {{ getLogisticsStageLabel(logistics.stage) }}</h4>
              <p>处理时间：{{ formatDateTime(logistics.recordedAt) }}</p>
              <p>地点：{{ logistics.location?.address }}</p>
              <p v-if="logistics.handledBy">处理人：{{ logistics.handledBy.username }}</p>
              <p v-if="logistics.temperature">
                运输温度：{{ logistics.temperature.min }}°C - {{ logistics.temperature.max }}°C
              </p>
              <p v-if="logistics.notes">备注：{{ logistics.notes }}</p>
            </el-card>
          </el-timeline-item>

          <!-- 销售阶段 -->
          <el-timeline-item
            v-for="(sales, index) in batchData.sales || []"
            :key="`sales-${index}`"
            timestamp="销售"
            type="info"
            :hollow="batchData.status === 'sales'"
          >
            <el-card class="timeline-card">
              <h4>销售记录</h4>
              <div class="sales-info">
                <div class="info-group">
                  <h5>商店信息</h5>
                  <p>商店名称：{{ sales.storeInfo?.storeName }}</p>
                  <p>商店地址：{{ sales.storeInfo?.storeAddress }}</p>
                  <p>商店类型：{{ sales.storeInfo?.storeType === 'physical' ? '实体店' : '线上店' }}</p>
                </div>
                <div class="info-group">
                  <h5>销售信息</h5>
                  <p>入库日期：{{ formatDate(sales.receiveDate) }}</p>
                  <p v-if="sales.sellDate">销售日期：{{ formatDate(sales.sellDate) }}</p>
                  <p>入库数量：{{ sales.quantity?.received }}份</p>
                  <p v-if="sales.quantity?.sold">已销售：{{ sales.quantity.sold }}份</p>
                  <p>零售价格：¥{{ sales.price?.retail }}</p>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-else-if="searched && !searching" class="empty-section">
      <el-empty
        description="未找到相关批次信息"
        :image-size="150"
      >
        <el-button type="primary" @click="clearSearch">重新查询</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { apiMethods } from '@/api'
import { ElMessage } from 'element-plus'
import {
  Search,
  Coffee,
  Connection,
  CopyDocument
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 状态
const searchId = ref('')
const searching = ref(false)
const searched = ref(false)
const batchData = ref(null)

// 方法
const handleSearch = async () => {
  if (!searchId.value.trim()) {
    ElMessage.warning('请输入批次ID')
    return
  }

  searching.value = true
  searched.value = true

  try {
    const response = await apiMethods.batches.getPublic(searchId.value.trim())
    
    if (response.data.success) {
      batchData.value = response.data.data.batch
      ElMessage.success('查询成功')
    } else {
      batchData.value = null
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    console.error('查询失败:', error)
    batchData.value = null
    ElMessage.error('查询失败，请检查批次ID是否正确')
  } finally {
    searching.value = false
  }
}

const copyBatchId = async () => {
  try {
    await navigator.clipboard.writeText(batchData.value.batchId)
    ElMessage.success('批次ID已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

const clearSearch = () => {
  searchId.value = ''
  batchData.value = null
  searched.value = false
}

const getStatusLabel = (status) => {
  const statusMap = {
    created: '已创建',
    production: '生产完成',
    logistics: '运输中',
    sales: '销售中',
    consumed: '已消费'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    created: 'info',
    production: 'warning',
    logistics: 'primary',
    sales: 'success',
    consumed: 'info'
  }
  return typeMap[status] || 'info'
}

const getLogisticsStageLabel = (stage) => {
  const stageMap = {
    pickup: '取货',
    transit: '运输中',
    warehouse: '仓储',
    delivery: '配送'
  }
  return stageMap[stage] || stage
}

const formatDate = (dateStr) => {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  // 如果URL中有批次ID，自动查询
  if (route.params.batchId) {
    searchId.value = route.params.batchId
    handleSearch()
  }
})
</script>

<style scoped>
.trace-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
}

.trace-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
}

.trace-header h1 {
  font-size: 32px;
  margin-bottom: 12px;
}

.trace-header p {
  font-size: 16px;
  opacity: 0.9;
}

.search-section {
  margin-bottom: 30px;
}

.search-card {
  max-width: 800px;
  margin: 0 auto;
}

.search-input {
  width: 100%;
}

.result-section {
  margin-bottom: 30px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.status-tag {
  margin-left: auto;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  gap: 8px;
}

.info-item label {
  font-weight: 500;
  color: #2c3e50;
  min-width: 80px;
  flex-shrink: 0;
}

.batch-id {
  font-family: monospace;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 13px;
}

.description {
  margin: 0;
  line-height: 1.5;
  color: #7f8c8d;
}

.trace-chain-card {
  margin-bottom: 20px;
}

.timeline-card {
  margin-left: 20px;
  border-left: 2px solid #e4e7ed;
  padding-left: 16px;
}

.timeline-card h4 {
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.timeline-card h5 {
  color: #409eff;
  margin: 12px 0 6px 0;
  font-size: 14px;
}

.timeline-card p {
  color: #7f8c8d;
  margin: 4px 0;
  font-size: 14px;
}

.info-group {
  margin-bottom: 16px;
}

.info-group:last-child {
  margin-bottom: 0;
}

.production-info,
.sales-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.empty-section {
  padding: 60px 20px;
  text-align: center;
}

/* 响应式 */
@media (max-width: 768px) {
  .trace-container {
    padding: 16px;
  }
  
  .trace-header {
    padding: 30px 20px;
  }
  
  .trace-header h1 {
    font-size: 24px;
  }
  
  .info-item {
    flex-direction: column;
    gap: 4px;
  }
  
  .info-item label {
    min-width: auto;
  }
  
  .production-info,
  .sales-info {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .timeline-card {
    margin-left: 0;
    padding-left: 12px;
  }
}

/* 时间线样式优化 */
:deep(.el-timeline-item__timestamp) {
  font-weight: 500;
  color: #409eff;
}

:deep(.el-timeline-item__node) {
  border-width: 3px;
}
</style>